package com.kuai.todo1.service;

import com.kuai.todo1.model.User;

import lombok.extern.slf4j.Slf4j;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class UserService {
    private static final String USER_DATA_FILE = "users.json";
    private List<User> users = new ArrayList<>();

    public UserService() {
        loadUsers();
    }

    private void loadUsers() {
        ObjectMapper objectMapper = new ObjectMapper();
        try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream(USER_DATA_FILE)) {
            if (inputStream != null) {
                users = objectMapper.readValue(inputStream,
                        objectMapper.getTypeFactory().constructCollectionType(List.class, User.class));
            } else {
                log.info("User data file not found.");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public Boolean registerUser(User user) {

        // 检查用户名是否已存在
        if (isUsernameExists(user.getUsername())) {
            return false;
        } else {
            users.add(user);
            saveUsers();
            return true;
        }
    }

    public boolean loginUser(String username, String password) {
        List<Integer> list = new ArrayList<Integer>();

        int[] arr = { 1, 2, 3, 4, 5, 6 };
        return users.stream().anyMatch(user -> username.equals(user.getUsername()) &&
                password.equals(user.getPassword()));
    }

    /**
     * 检查用户名是否已存在
     *
     * @param username 用户名
     * @return 如果用户名已存在，返回 true；否则返回 false
     */
    private boolean isUsernameExists(String username) {
        // 从文件中加载用户数据并检查用户名是否存在
        List<User> existingUsers = loadUsersFromFile();
        return existingUsers.stream().anyMatch(existingUser -> existingUser.getUsername().equals(username));
    }

    private List<User> loadUsersFromFile() {
        ObjectMapper objectMapper = new ObjectMapper();
        List<User> existingUsers = new ArrayList<>();
        try {
            URL resource = getClass().getClassLoader().getResource(USER_DATA_FILE);
            if (resource != null) {
                File file = new File(resource.toURI());
                existingUsers = objectMapper.readValue(file,
                        objectMapper.getTypeFactory().constructCollectionType(List.class, User.class));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return existingUsers;
    }

    private void saveUsers() {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            URL resource = getClass().getClassLoader().getResource(USER_DATA_FILE);
            if (resource != null) {
                File file = new File(resource.toURI());
                objectMapper.writeValue(file, users);
            }
        } catch (Exception e) {
            e.printStackTrace(); // 打印异常信息
        }
    }
}
